<?php

namespace Plugins\AdminBasic\Http\Admin\Service;

use App\Util\EasySearchMacro\GlobalSearch;
use App\Util\Helper;
use Sc\Util\ImitateAopProxy\AopProxyTrait;
use App\Exception\ApiMessageException;
use App\Http\Admin\Service\Traits\DestroyServiceTrait;
use App\Http\Admin\Service\Traits\StoreServiceTrait;
use App\Http\Admin\Service\Traits\SwitchServiceTrait;
use App\Http\Admin\Service\Traits\UpdateServiceTrait;
use App\Util\EasySearch;
use Plugins\AdminBasic\Models\BasicRole;


/**
 * 管理员角色
 */
class RoleService
{

    use AopProxyTrait;
    use StoreServiceTrait;
    use UpdateServiceTrait;
    use DestroyServiceTrait;
    use SwitchServiceTrait;

    /**
     * 获取模型
     */
    public function getModel(int $id = null): BasicRole
    {
        return $id ? BasicRole::find($id) :new BasicRole();
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function lists(): array
    {
        $query = BasicRole::select(["id","name","describe","create_time"]);

        return EasySearch::create($query)->addMacro(GlobalSearch::class, "name")->getData();
    }

    /**
     * @param int $id
     * @param array $routeIds
     * @return void
     * @throws ApiMessageException
     */
    public function savePermission(int $id, array $routeIds): void
    {
        $role = BasicRole::find($id);

        if (!$role) {
            throw new ApiMessageException('角色信息错误');
        }

        $role->route_ids = $routeIds;
        $role->save();

        Helper::getContainer(RolePermissionsService::class)->cacheRoleRouteIds($role);
    }

}